<!-- 成员管理组件 -->
<template>
  <div>
    <el-dialog
        v-model="dialogVisible"
        title="文档成员"
        width="400px"
        @close="handleClose"
    >
      <div class="member-list">
        <div v-for="collaborator in collaborators" :key="collaborator.userId" class="member-item">
          <div class="member-info">
            <span class="member-name">{{ collaborator.username }}</span>

            <!-- 可编辑的权限选择器 -->
            <el-dropdown
                v-if="canEditPermission(collaborator)"
                @command="(command) => handleCommand(collaborator, command)"
                trigger="click"
            >
            <el-tag
                :type="getPermissionTagType(collaborator.permissionType)"
                size="small"
                class="permission-tag"
            >
              {{ formatPermission(collaborator.permissionType) }}
            </el-tag>

              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                      v-for="perm in availablePermissions"
                      :key="perm.value"
                      :command="perm.value"
                      :disabled="perm.value === collaborator.permissionType && perm.value !== 'REMOVE'"
                  >
                    {{ perm.label }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <!-- 不可编辑的权限显示 -->
            <el-tag
                v-else
                :type="getPermissionTagType(collaborator.permissionType)"
                size="small"
            >
              {{ formatPermission(collaborator.permissionType) }}
            </el-tag>
          </div>
          <div class="member-role">
            {{ getRoleDescription(collaborator.permissionType) }}
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="closeDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {computed, ref, watch} from 'vue'
import {getDocCollaborators} from '@/api/document'
import {ElMessage} from "element-plus";
import type {GrantPermissionRequest} from "@/types";
import {getUserId} from "@/utils/auth.ts";
import {grantPermission, removeDocPermission} from "@/api/permission.ts";

interface Collaborator {
  userId: number
  username: string
  documentId: string
  permissionType: string
}

interface PermissionOption {
  value: string
  label: string
}

const props = defineProps<{
  docId: string
  visible: boolean
  currentUserPermission: string // 当前用户的权限，用于判断能否修改他人权限
}>()

const emit = defineEmits(['update:visible', 'permission-changed'])

// 使用ref来管理内部dialog状态
const internalVisible = ref(props.visible)

// 可用权限选项
const availablePermissions: PermissionOption[] = [
  { value: 'READ', label: '查看' },
  { value: 'EDIT', label: '编辑' },
  { value: 'REMOVE', label: '移除'} // 新增移除选项
  // { value: 'MANAGE', label: '管理' }
]

// 监听props.visible变化
watch(() => props.visible, (newVal) => {
  internalVisible.value = newVal
})

// 监听对话框可见状态变化
watch(internalVisible, (newVal) => {
  if (newVal) {
    fetchCollaborators() // 对话框打开时获取数据
  }
})

// 关闭弹窗的处理函数
const closeDialog = () => {
  internalVisible.value = false
  emit('update:visible', false)
}

// 处理弹窗关闭事件（包括点击X和点击遮罩层）
const handleClose = () => {
  emit('update:visible', false)
}

// 计算属性用于双向绑定
const dialogVisible = computed({
  get: () => internalVisible.value,
  set: (value) => {
    internalVisible.value = value
    if (!value) {
      emit('update:visible', false)
    }
  }
})

const collaborators = ref<Collaborator[]>([])
const isLoading = ref(false)

const fetchCollaborators = async () => {
  try {
    isLoading.value = true
    collaborators.value = await getDocCollaborators(props.docId)
  } catch (error) {
    console.error('获取协作者失败:', error)
    ElMessage.error('获取协作者列表失败')
    // 可以根据需要添加错误提示
  } finally {
    isLoading.value = false
  }
}

// 检查当前用户是否有权限修改该协作者的权限
const canEditPermission = (collaborator: Collaborator) => {
  // 这里根据业务逻辑实现，例如：
  // 1. 当前用户必须有MANAGE权限
  // 2. 不能修改自己的权限
  // 3. 不能修改权限比自己高的用户
  return props.currentUserPermission === 'MANAGE' &&
      collaborator.userId !== parseInt(getUserId() || '0')
}

// 处理下拉菜单命令
const handleCommand = async (collaborator: Collaborator, command: string) => {
  if (command === 'REMOVE') {
    await handleRemoveCollaborator(collaborator)
  } else {
    await handlePermissionChange(collaborator, command)
  }
}

// 处理移除协作者
const handleRemoveCollaborator = async (collaborator: Collaborator) => {
  try {
    // 调用移除API
    const success = await removeDocPermission(
        collaborator.userId.toString(),
        props.docId
    )

    if (success) {
      // 从本地列表中移除
      collaborators.value = collaborators.value.filter(
          c => c.userId !== collaborator.userId
      )

      ElMessage.success('成员移除成功')
      emit('permission-changed', {
        userId: collaborator.userId,
        removed: true
      })
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除成员失败:', error)
      ElMessage.error('移除成员失败')
    }
  }
}

// 处理权限变更
const handlePermissionChange = async (collaborator: Collaborator, newPermission: string) => {
  try {
    const payload: GrantPermissionRequest = {
      userId: collaborator.userId.toString() || '',
      documentId: props.docId,
      permissionType: newPermission,
      grantedBy: getUserId() || ''
    }
    // 调用API更新权限
    await grantPermission(payload);

    // 更新本地数据
    const index = collaborators.value.findIndex(c => c.userId === collaborator.userId)
    if (index !== -1) {
      collaborators.value[index].permissionType = newPermission
    }

    // 通知父组件权限已变更
    emit('permission-changed', {
      userId: collaborator.userId,
      newPermission
    })

    // 可以添加成功提示
    ElMessage.success('修改用户权限成功')
  } catch (error) {
    console.error('修改用户权限失败:', error)
    ElMessage.error('修改用户权限失败')
  }
}

const formatPermission = (permission: string) => {
  const map: Record<string, string> = {
    'READ': '可阅读',
    'EDIT': '可编辑',
    'MANAGE': '可管理'
  }
  return map[permission] || permission
}

const getPermissionTagType = (permission: string) => {
  const map: Record<string, string> = {
    'READ': 'info',
    'EDIT': 'warning',
    'MANAGE': 'success'
  }
  return map[permission] || ''
}

const getRoleDescription = (permission: string) => {
  const map: Record<string, string> = {
    'READ': '可以查看文档',
    'EDIT': '可以编辑文档',
    'MANAGE': '可以管理文档及成员'
  }
  return map[permission] || ''
}
</script>

<style scoped>
.member-list {
  max-height: 400px;
  overflow-y: auto;
}

.member-item {
  display: flex;
  flex-direction: column;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.member-item:last-child {
  border-bottom: none;
}

.member-info {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.member-name {
  margin-right: 8px;
  font-weight: 500;
}

.member-role {
  font-size: 12px;
  color: #888;
}
</style>